<template>
  <div class="product-manage">
    <div class="header">
      <el-button type="primary" @click="showAddDialog">添加商品</el-button>
      <el-input
        v-model="searchQuery"
        placeholder="输入商品名称搜索"
        class="search-input"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <el-table :data="productList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="商品图片" width="120">
        <template slot-scope="scope">
          <img :src="getImagePath(scope.row.mainImage)" class="product-img">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="categoryName" label="分类"></el-table-column>
      <el-table-column prop="price" label="价格" width="120"></el-table-column>
      <el-table-column prop="stock" label="库存" width="120"></el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="70%">
      <el-form :model="productForm" :rules="rules" ref="productForm" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
              v-model="productForm.categoryId"
              :options="categoryOptions"
              :props="{ checkStrictly: true, emitPath: false }"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品主图">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleMainImageSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="productForm.mainImage" :src="getImagePath(productForm.mainImage)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="适用年龄" prop="ageRange">
          <el-select v-model="productForm.ageRange">
            <el-option label="新生儿" value="newborn"></el-option>
            <el-option label="婴儿期" value="infant"></el-option>
            <el-option label="幼儿期" value="toddler"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标用户" prop="targetUser">
          <el-select v-model="productForm.targetUser">
            <el-option label="婴儿" value="baby"></el-option>
            <el-option label="妈妈" value="mother"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品详情" prop="detail">
          <el-input type="textarea" v-model="productForm.detail" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList, saveProduct, deleteProduct, updateProductStatus } from '@/api/product'
import { getCategoryTree } from '@/api/product.js'

export default {
  name: 'ProductManage',
  data() {
    return {
      searchQuery: '',
      productList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '添加商品',
      categoryOptions: [],
      productForm: {
        name: '',
        categoryId: '', // 确保类型正确
        price: 0,
        stock: 0,
        mainImage: '',
        detail: '',
        ageRange: '',
        targetUser: ''
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }]
      },
      // uploadUrl : `http://localhost:8080/api/api/products/upload?productId=${this.productForm.id}`
      // uploadUrl: "http://localhost:8080/api/api/products" + '/upload？' // 定义上传文件路径
      uploadUrl:''
    }
  },
  created() {
    this.getList()
    this.getCategoryOptions()
  },
  methods: {
    getImagePath(imageName) {
      console.log('Image Name:', imageName);
      if (imageName) {
        try {
          return require(`@/assets/${imageName}`);
        } catch (e) {
          console.error('Image not found:', imageName, e);
          return require('@/assets/logo.jpg'); // 返回默认图片
        }
      }
      return require('@/assets/logo.jpg'); // 返回默认图片
    },
    async getList() {
      try {
        const { data } = await getProductList({
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery
        })
        this.productList = data.list
        this.total = data.total
      } catch (error) {
        this.$message.error('获取商品列表失败')
      }
    },
    async getCategoryOptions() {
      try {
        const { data } = await getCategoryTree()
        this.categoryOptions = this.formatCategoryOptions(data)
      } catch (error) {
        this.$message.error('获取分类列表失败')
      }
    },
    formatCategoryOptions(categories) {
      return categories.map(category => ({
        value: category.id,
        label: category.name,
        children: category.children ? this.formatCategoryOptions(category.children) : []
      }))
    },
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },
    showAddDialog() {
      this.dialogTitle = '添加商品'
      this.productForm = {
        name: '',
        categoryId: '',
        price: 0,
        stock: 0,
        mainImage: '',
        detail: '',
        ageRange: '',
        targetUser: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      this.productForm = { ...row }
      this.dialogVisible = true
    },
    async handleSubmit() {
      this.$refs.productForm.validate(async valid => {
        if (valid) {
          try {
            await saveProduct(this.productForm)
            this.dialogVisible = false
            this.getList()
            this.$message.success('保存成功')
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    }
    ,
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该商品?', '提示', {
          type: 'warning'
        })
        await deleteProduct(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    async handleStatusChange(row) {
      try {
        console.log('132321', row.status)
        console.log('132321', row.id)
        await updateProductStatus(row.id, row.status)
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        row.status = row.status === 1 ? 0 : 1
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      this.uploadUrl = `http://localhost:8080/api/api/products/upload?productId=${this.productForm.id}`;
      console.log('this.uploadUrl', this.uploadUrl)
      return isJPG && isLt2M;
    },
    handleMainImageSuccess(res) {
      if (res.code === 200) {
        this.productForm.mainImage = res.data;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error('图片上传失败');
      }
    }
  }
}
</script>

<style scoped>
.product-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.search-input {
  width: 300px;
}
.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>